/*
 *	Generate the syscall functions
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "syscall_name.h"

static char namebuf[128];
static char *cpu;

static void write_call(int n)
{
  FILE *fp;
  snprintf(namebuf, 128, "fuzix%s/syscall_%s.s", cpu, syscall_name[n]);
  fp = fopen(namebuf, "w");
  if (fp == NULL) {
    perror(namebuf);
    exit(1);
  }
  fprintf(fp, "\t.area _CODE\n\n");
  fprintf(fp, "\t.globl __syscall\n");
  fprintf(fp, "\t.globl _%s\n\n", syscall_name[n]);
  fprintf(fp, "_%s:\n\tld a, #%d\n", syscall_name[n], n);
  fprintf(fp, "\tjp __syscall\n");
  fclose(fp);
}

static void write_call_table(void)
{
  int i;
  for (i = 0; i < NR_SYSCALL; i++)
    write_call(i);
}

static void write_makefile(void)
{
  int i;
  char path[256];
  FILE *fp;

  snprintf(path, 256, "fuzix%s/Makefile", cpu);

  fp = fopen(path, "w");
  if (fp == NULL) {
    perror("Makefile");
    exit(1);
  }
  fprintf(fp, "# Autogenerated by tools/syscall\n");
  if (*cpu == 'z' || *cpu == 'e')
    fprintf(fp, "CROSS_AS=sdasz80\nCROSS_LD=sdldz80\nCROSS_AR=sdar\n");
  else
    fprintf(fp, "CROSS_AS=sdasrab\nCROSS_LD=sdldz80\nCROSS_AR=sdar\n");
  fprintf(fp, "ASOPTS=\n\n");
  fprintf(fp, "ASYS=syscall$(PLATFORM).s\n");
  fprintf(fp, "ASRCS = syscall_%s.s\n", syscall_name[0]);
  for (i = 1; i < NR_SYSCALL; i++)
    fprintf(fp, "ASRCS += syscall_%s.s\n", syscall_name[i]);
  fprintf(fp, "\n\nASRCALL = $(ASRCS) $(ASYS)\n");
  fprintf(fp, "\nAOBJS = $(ASRCALL:.s=.rel)\n\n");
  fprintf(fp, "syslib.lib: $(AOBJS)\n");
  fprintf(fp, "\techo $(AOBJS) >syslib.l\n");
  fprintf(fp, "\t$(CROSS_AR) rc syslib.lib $(AOBJS)\n\n");
  fprintf(fp, "$(AOBJS): %%.rel: %%.s\n");
  fprintf(fp, "\t$(CROSS_AS) $(ASOPTS) -o $*.rel $<\n\n");
  fprintf(fp, "clean:\n");
  fprintf(fp, "\trm -f $(AOBJS) $(ASRCS) syslib.lib *~\n\n");
  fclose(fp);
}

int main(int argc, char *argv[])
{
  cpu = argv[1];
  if (cpu == NULL)
    cpu = "z80";
  write_makefile();
  write_call_table();
  exit(0);
}
